package com.acg.auth.service.impl;

import com.acg.auth.mapper.SysUserRoleMapper;
import com.acg.auth.pojo.SysRole;
import com.acg.auth.mapper.SysRoleMapper;
import com.acg.auth.pojo.SysUserRole;
import com.acg.auth.service.SysRoleService;
import com.acg.auth.vo.AssginRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author acg
 * @since 2025-08-08
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Resource
    private SysUserRoleMapper userRoleMapper;

    /**
     * 根据用户主键获取角色数据
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> findRoleByAdminId(Long userId) {

        // 1 创建条件
        LambdaQueryWrapper<SysUserRole> lqw= new LambdaQueryWrapper<>();
        lqw.eq(SysUserRole::getUserId, userId);

        // 2、进行查找      // roleUser 表记录
        List<SysUserRole> list = userRoleMapper.selectList(lqw);

        // 3 获取角色id(该用户 下对应的角色id)
        List<Long> roleIdsByUserId = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        List<SysRole> assginRoleList = new ArrayList<>();
        // 判断角色id 不为空进行查找
        if (!CollectionUtils.isEmpty(roleIdsByUserId)) {
            // 3.1 查找 角色ids  查找角色信息
            assginRoleList = this.listByIds(roleIdsByUserId);
        }


        // 4 查询所有的角色
        List<SysRole> roleList = this.list();

        // 5 构建返回值
        Map<String, Object> map = new HashMap<>();
        map.put("assginRoleList", assginRoleList);      // 用户包含的角色
        map.put("allRolesList", roleList);              // 全部角色

        return map;
    }

    @Override
    @Transactional      // 添加声明式事务
    public void doAssign(AssginRoleVo assginRoleVo) {
        // 1、 删除原有的userid的所有角色信息
        // 1.1 构建删除条件
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, assginRoleVo.getUserId());
        int delete = this.userRoleMapper.delete(wrapper);

        // 2、添加新的角色信息
        // 增加
        // 要新增角色id 列表
        List<Long> roleIds = assginRoleVo.getRoleIds();
        for (Long roleId : roleIds) {
            // 创建SysUserRole 对象
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            // 增加数据
            this.userRoleMapper.insert(sysUserRole);
        }
    }

}
